# -*- coding: utf-8 -*-

# Copyright (c) 2025 Lijiang
# Licensed under the MIT License
# See LICENSE file for details

"""
主窗口UI类
"""

import os
import logging
from typing import List, Dict
from PyQt6.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
    QPushButton, QLabel, QSlider, QProgressBar, QTableWidget, QTableWidgetItem,
    QGroupBox, QFileDialog, QMessageBox, QSplitter, QHeaderView,
    QAbstractItemView, QFrame, QSizePolicy
)
from PyQt6.QtCore import Qt, QTimer, pyqtSignal
from PyQt6.QtGui import QFont, QDragEnterEvent, QDropEvent, QPixmap, QPainter, QColor, QIcon

from .styles import get_dark_style
from core.file_handler import FileHandler
from core.video_compressor import VideoCompressor
from config import (
    get_window_config, get_compression_config, get_ffmpeg_config,
    THREAD_POOL_CONFIG, VIDEO_FILE_FILTER, WINDOW_CONFIG
)

logger = logging.getLogger(__name__)


class FileListWidget(QTableWidget):
    """文件列表组件"""
    
    def __init__(self):
        super().__init__()
        self.setup_ui()
    
    def setup_ui(self):
        """设置UI"""
        ############################### 设置列 ###############################
        self.setColumnCount(4)
        self.setHorizontalHeaderLabels(['文件名', '格式', '大小', '状态'])
        
        ############################### 设置表格属性 ###############################
        self.setAlternatingRowColors(True)
        self.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
        self.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)
        self.setSortingEnabled(True)
        
        ############################### 设置列宽 ###############################
        header = self.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)  # 文件名列自适应
        header.setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents)  # 格式列
        header.setSectionResizeMode(2, QHeaderView.ResizeMode.ResizeToContents)  # 大小列
        header.setSectionResizeMode(3, QHeaderView.ResizeMode.ResizeToContents)  # 状态列
        
        ############################### 设置行高 ###############################
        self.verticalHeader().setDefaultSectionSize(40)
    
    def add_file(self, file_path: str) -> bool:
        """添加文件到列表"""
        if not FileHandler.is_video_file(file_path):
            return False
        
        ############################### 检查是否已存在 ###############################
        for row in range(self.rowCount()):
            if self.item(row, 0).text() == os.path.basename(file_path):
                return False
        
        ############################### 获取文件信息 ###############################
        file_info = FileHandler.get_file_info(file_path)
        
        ############################### 添加新行 ###############################
        row = self.rowCount()
        self.insertRow(row)
        
        ############################### 设置文件信息 ###############################
        self.setItem(row, 0, QTableWidgetItem(file_info['name']))
        self.setItem(row, 1, QTableWidgetItem(file_info['format']))
        self.setItem(row, 2, QTableWidgetItem(file_info['size']))
        self.setItem(row, 3, QTableWidgetItem('待压缩'))
        
        ############################### 存储完整路径到第一列的用户数据 ###############################
        self.item(row, 0).setData(Qt.ItemDataRole.UserRole, file_path)
        
        return True
    
    def remove_selected_files(self):
        """删除选中的文件"""
        selected_rows = sorted(set(item.row() for item in self.selectedItems()), reverse=True)
        for row in selected_rows:
            self.removeRow(row)
    
    def clear_all(self):
        """清空所有文件"""
        self.setRowCount(0)
    
    def get_file_paths(self) -> List[str]:
        """获取所有文件路径"""
        paths = []
        for row in range(self.rowCount()):
            item = self.item(row, 0)
            if item:
                path = item.data(Qt.ItemDataRole.UserRole)
                if path:
                    paths.append(path)
        return paths
    
    def update_file_status(self, file_path: str, status: str):
        """更新文件状态"""
        for row in range(self.rowCount()):
            item = self.item(row, 0)
            if item and item.data(Qt.ItemDataRole.UserRole) == file_path:
                self.setItem(row, 3, QTableWidgetItem(status))
                break


class CompressionSettingsWidget(QWidget):
    """压缩设置组件"""
    
    compression_ratio_changed = pyqtSignal(float)
    
    def __init__(self):
        super().__init__()
        self.setup_ui()
    
    def setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout(self)
        
        ############################### 压缩比例控制组 ###############################
        ratio_group = QGroupBox("⚙️ 压缩设置")
        ratio_layout = QGridLayout(ratio_group)
        
        ############################### 压缩比例标签 ###############################
        self.ratio_label = QLabel("压缩比例: 0%")
        self.ratio_label.setProperty("class", "subtitle")
        self.ratio_label.setFont(QFont("Segoe UI", 11, QFont.Weight.Bold))
        ratio_layout.addWidget(self.ratio_label, 0, 0, 1, 2)
        
        ############################### 压缩比例滑块 ###############################
        compression_config = get_compression_config()
        self.ratio_slider = QSlider(Qt.Orientation.Horizontal)
        self.ratio_slider.setRange(compression_config['min_ratio'], compression_config['max_ratio'])
        self.ratio_slider.setValue(compression_config['default_ratio'])
        self.ratio_slider.setTickPosition(QSlider.TickPosition.TicksBelow)
        self.ratio_slider.setTickInterval(compression_config['tick_interval'])
        self.ratio_slider.valueChanged.connect(self.on_ratio_changed)
        ratio_layout.addWidget(self.ratio_slider, 1, 0, 1, 2)
        
        ############################### 比例范围标签 ###############################
        range_layout = QHBoxLayout()
        range_layout.addWidget(QLabel(f"{compression_config['min_ratio']}%"))
        range_layout.addStretch()
        range_layout.addWidget(QLabel(f"{compression_config['max_ratio']}%"))
        ratio_layout.addLayout(range_layout, 2, 0, 1, 2)
        
        ############################### 预估输出大小 ###############################
        self.size_label = QLabel("预估输出大小: --")
        self.size_label.setProperty("class", "subtitle")
        self.size_label.setFont(QFont("Segoe UI", 9))
        ratio_layout.addWidget(self.size_label, 3, 0, 1, 2)
        
        layout.addWidget(ratio_group)
    
    def on_ratio_changed(self, value):
        """压缩比例改变时的处理"""
        ratio = value / 100.0
        self.ratio_label.setText(f"压缩比例: {value}%")
        self.compression_ratio_changed.emit(ratio)
    
    def get_compression_ratio(self) -> float:
        """获取当前压缩比例"""
        return self.ratio_slider.value() / 100.0
    
    def set_compression_ratio(self, ratio: float):
        """设置压缩比例"""
        value = int(ratio * 100)
        self.ratio_slider.setValue(value)
    
    def update_estimated_size(self, size: str):
        """更新预估输出大小"""
        self.size_label.setText(f"预估输出大小: {size}")
    
    def set_compression_enabled(self, enabled: bool):
        """设置压缩控制是否可用"""
        self.ratio_slider.setEnabled(enabled)


class OperationControlWidget(QWidget):
    """操作控制组件"""
    
    def __init__(self, main_window=None):
        super().__init__()
        self.main_window = main_window  # 保存主窗口引用
        self.setup_ui()
    
    def setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout(self)
        
        ############################### 控制按钮组 ###############################
        control_group = QGroupBox("🎮 操作控制")
        control_layout = QVBoxLayout(control_group)
        
        ############################### 按钮布局 ###############################
        button_layout = QHBoxLayout()
        
        self.add_files_btn = QPushButton("添加文件")
        self.add_files_btn.clicked.connect(self.emit_add_files)
        button_layout.addWidget(self.add_files_btn)
        
        self.clear_files_btn = QPushButton("清空列表")
        self.clear_files_btn.clicked.connect(self.emit_clear_files)
        button_layout.addWidget(self.clear_files_btn)
        
        control_layout.addLayout(button_layout)
        
        ############################### 压缩按钮 ###############################
        self.start_btn = QPushButton("开始压缩")
        self.start_btn.setObjectName("startButton")
        self.start_btn.clicked.connect(self.emit_start_compression)
        control_layout.addWidget(self.start_btn)
        
        ############################### 取消按钮 ###############################
        self.cancel_btn = QPushButton("取消压缩")
        self.cancel_btn.setObjectName("cancelButton")
        self.cancel_btn.setEnabled(False)
        self.cancel_btn.clicked.connect(self.emit_cancel_compression)
        control_layout.addWidget(self.cancel_btn)
        
        layout.addWidget(control_group)
    
    def set_compression_enabled(self, enabled: bool):
        """设置压缩控制是否可用"""
        self.start_btn.setEnabled(enabled)
        self.cancel_btn.setEnabled(not enabled)
    
    def emit_add_files(self):
        """发出添加文件信号"""
        logger.info("用户点击添加文件按钮")
        try:
            if self.main_window:
                self.main_window.add_files()
            else:
                logger.error("主窗口引用为空，无法添加文件")
        except Exception as e:
            logger.error(f"添加文件时发生错误: {e}", exc_info=True)
    
    def emit_clear_files(self):
        """发出清空文件信号"""
        logger.info("用户点击清空文件按钮")
        try:
            if self.main_window:
                self.main_window.clear_files()
            else:
                logger.error("主窗口引用为空，无法清空文件")
        except Exception as e:
            logger.error(f"清空文件时发生错误: {e}", exc_info=True)
    
    def emit_start_compression(self):
        """发出开始压缩信号"""
        logger.info("用户点击开始压缩按钮")
        try:
            if self.main_window:
                self.main_window.start_compression()
            else:
                logger.error("主窗口引用为空，无法开始压缩")
        except Exception as e:
            logger.error(f"开始压缩时发生错误: {e}", exc_info=True)
    
    def emit_cancel_compression(self):
        """发出取消压缩信号"""
        logger.info("用户点击取消压缩按钮")
        try:
            if self.main_window:
                self.main_window.cancel_compression()
            else:
                logger.error("主窗口引用为空，无法取消压缩")
        except Exception as e:
            logger.error(f"取消压缩时发生错误: {e}", exc_info=True)


class ProgressWidget(QWidget):
    """进度显示组件"""
    
    def __init__(self):
        super().__init__()
        self.setup_ui()
    
    def setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout(self)
        
        ############################### 进度组 ###############################
        progress_group = QGroupBox("📊 压缩进度")
        progress_layout = QVBoxLayout(progress_group)
        
        ############################### 总体进度 ###############################
        self.overall_progress = QProgressBar()
        self.overall_progress.setRange(0, 100)
        self.overall_progress.setValue(0)
        overall_label = QLabel("📈 总体进度:")
        overall_label.setProperty("class", "subtitle")
        progress_layout.addWidget(overall_label)
        progress_layout.addWidget(self.overall_progress)
        
        ############################### 当前文件进度 ###############################
        self.current_progress = QProgressBar()
        self.current_progress.setRange(0, 100)
        self.current_progress.setValue(0)
        current_label = QLabel("📄 当前文件:")
        current_label.setProperty("class", "subtitle")
        progress_layout.addWidget(current_label)
        progress_layout.addWidget(self.current_progress)
        
        ############################### 状态标签 ###############################
        self.status_label = QLabel("准备就绪")
        self.status_label.setWordWrap(True)
        status_title = QLabel("🔍 状态:")
        status_title.setProperty("class", "subtitle")
        progress_layout.addWidget(status_title)
        progress_layout.addWidget(self.status_label)
        
        ############################### 文件信息标签 ###############################
        self.file_info_label = QLabel("")
        self.file_info_label.setWordWrap(True)
        self.file_info_label.setProperty("class", "subtitle")
        progress_layout.addWidget(self.file_info_label)
        
        layout.addWidget(progress_group)
    
    def update_overall_progress(self, value: int):
        """更新总体进度"""
        self.overall_progress.setValue(value)
    
    def update_current_progress(self, value: int):
        """更新当前文件进度"""
        self.current_progress.setValue(value)
    
    def update_status(self, status: str):
        """更新状态"""
        self.status_label.setText(status)
    
    def update_file_info(self, info: Dict):
        """更新文件信息"""
        if info:
            text = f"原始大小: {info.get('original_size', '--')}\n"
            text += f"压缩后: {info.get('compressed_size', '--')}\n"
            text += f"压缩比: {info.get('compression_ratio', '--')}"
            self.file_info_label.setText(text)
        else:
            self.file_info_label.setText("")


class MainWindow(QMainWindow):
    """主窗口类"""
    
    def __init__(self):
        super().__init__()
        logger.info("初始化主窗口组件")
        
        try:
            logger.info("创建文件列表组件")
            self.file_list = FileListWidget()
            
            logger.info("创建压缩设置组件")
            self.compression_settings = CompressionSettingsWidget()
            
            logger.info("创建操作控制组件")
            self.operation_control = OperationControlWidget(self)
            
            logger.info("创建进度显示组件")
            self.progress_widget = ProgressWidget()
            
            logger.info("创建视频压缩器（FFmpeg模式）")
            # 使用FFmpeg模式，支持真实进度跟踪
            self.compressor = VideoCompressor(max_workers=THREAD_POOL_CONFIG['max_workers'])
            
            self.current_workers = []
            self.total_files = 0
            self.completed_files = 0
            
            logger.info("设置UI布局")
            self.setup_ui()
            
            logger.info("设置信号连接")
            self.setup_connections()
            
            logger.info("设置拖拽功能")
            self.setup_drag_drop()
            
            logger.info("主窗口初始化完成")
            
        except Exception as e:
            logger.error(f"主窗口初始化失败: {e}", exc_info=True)
            raise
    
    def setup_ui(self):
        """设置UI"""
        window_config = get_window_config()
        self.setWindowTitle(window_config['title'])
        self.setMinimumSize(window_config['min_width'], window_config['min_height'])
        self.resize(window_config['default_width'], window_config['default_height'])
        
        ############################### 设置窗口图标 ###############################
        self.set_window_icon()
        
        ############################### 应用深色主题 ###############################
        self.setStyleSheet(get_dark_style())
        
        ############################### 创建中央部件 ###############################
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        ############################### 创建主布局 ###############################
        main_layout = QHBoxLayout(central_widget)
        
        ############################### 创建分割器 ###############################
        splitter = QSplitter(Qt.Orientation.Horizontal)
        
        ############################### 左侧：文件列表 ###############################
        left_widget = QWidget()
        left_layout = QVBoxLayout(left_widget)
        
        ############################### 添加标题 ###############################
        file_list_title = QLabel("📁 文件列表")
        file_list_title.setProperty("class", "title")
        left_layout.addWidget(file_list_title)
        left_layout.addWidget(self.file_list)
        
        ############################### 右侧：设置、控制和进度 ###############################
        right_widget = QWidget()
        right_layout = QVBoxLayout(right_widget)
        right_layout.setSpacing(15)
        right_layout.setContentsMargins(5, 5, 5, 5)
        
        ############################### 添加三个独立的组件，设置合适的大小比例 ###############################
        right_layout.addWidget(self.compression_settings, 1)  # 压缩设置占1份
        right_layout.addWidget(self.operation_control, 1)     # 操作控制占1份
        right_layout.addWidget(self.progress_widget, 2)       # 进度显示占2份
        
        ############################### 添加到分割器 ###############################
        splitter.addWidget(left_widget)
        splitter.addWidget(right_widget)
        splitter.setSizes([500, 500])  # 更平衡的比例
        
        main_layout.addWidget(splitter)
    
    def setup_connections(self):
        """设置信号连接"""
        ############################### 压缩比例改变 ###############################
        self.compression_settings.compression_ratio_changed.connect(self.on_compression_ratio_changed)
        
        ############################### 定时器用于更新进度 ###############################
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_progress)
        self.timer.start(THREAD_POOL_CONFIG['progress_update_interval'])  # 使用配置的更新间隔
    
    def setup_drag_drop(self):
        """设置拖拽功能"""
        self.setAcceptDrops(True)
    
    def dragEnterEvent(self, event: QDragEnterEvent):
        """拖拽进入事件"""
        if event.mimeData().hasUrls():
            event.acceptProposedAction()
        else:
            event.ignore()
    
    def dropEvent(self, event: QDropEvent):
        """拖拽放下事件"""
        files = [url.toLocalFile() for url in event.mimeData().urls()]
        self.add_files_from_paths(files)
        event.acceptProposedAction()
    
    def add_files(self):
        """添加文件对话框"""
        logger.info("打开文件选择对话框")
        try:
            files, _ = QFileDialog.getOpenFileNames(
                self,
                "选择视频文件",
                "",
                VIDEO_FILE_FILTER
            )
            logger.info(f"用户选择了 {len(files) if files else 0} 个文件")
            if files:
                self.add_files_from_paths(files)
        except Exception as e:
            logger.error(f"文件选择对话框出错: {e}", exc_info=True)
    
    def add_files_from_paths(self, file_paths: List[str]):
        """从路径列表添加文件"""
        added_count = 0
        for file_path in file_paths:
            if self.file_list.add_file(file_path):
                added_count += 1
        
        if added_count > 0:
            self.show_message(f"成功添加 {added_count} 个文件", "信息")
            # 更新预估输出大小
            self.update_estimated_output_size(self.compression_settings.get_compression_ratio())
        else:
            self.show_message("没有添加任何有效文件", "警告")
    
    def clear_files(self):
        """清空文件列表"""
        if self.file_list.rowCount() > 0:
            reply = QMessageBox.question(
                self, "确认清空", "确定要清空所有文件吗？",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
            )
            if reply == QMessageBox.StandardButton.Yes:
                self.file_list.clear_all()
                self.progress_widget.update_overall_progress(0)
                self.progress_widget.update_current_progress(0)
                self.progress_widget.update_status("准备就绪")
                self.progress_widget.update_file_info({})
                # 更新预估输出大小
                self.update_estimated_output_size(self.compression_settings.get_compression_ratio())
    
    def start_compression(self):
        """开始压缩"""
        file_paths = self.file_list.get_file_paths()
        if not file_paths:
            self.show_message("请先添加要压缩的文件", "警告")
            return
        
        if self.current_workers:
            self.show_message("已有压缩任务在进行中", "警告")
            return
        
        # 设置状态
        self.total_files = len(file_paths)
        self.completed_files = 0
        self.compression_settings.set_compression_enabled(False)
        self.operation_control.set_compression_enabled(False)
        self.progress_widget.update_overall_progress(0)
        self.progress_widget.update_status("准备开始压缩...")
        
        # 开始压缩每个文件（使用线程池模式）
        compression_ratio = self.compression_settings.get_compression_ratio()
        for file_path in file_paths:
            output_path = FileHandler.generate_output_path(file_path, compression_ratio)
            task_id = self.compressor.compress_video(
                file_path, output_path, compression_ratio,
                progress_callback=self.on_file_progress_updated,
                status_callback=self.on_file_status_updated,
                finished_callback=self.on_file_compression_finished,
                file_info_callback=self.on_file_info_updated,
                use_thread_pool=True  # 使用线程池模式
            )
            self.current_workers.append(task_id)
    
    def cancel_compression(self):
        """取消压缩"""
        if self.current_workers:
            reply = QMessageBox.question(
                self, "确认取消", "确定要取消所有压缩任务吗？",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
            )
            if reply == QMessageBox.StandardButton.Yes:
                self.compressor.cancel_all()
                self.current_workers.clear()
                self.compression_settings.set_compression_enabled(True)
                self.operation_control.set_compression_enabled(True)
                self.progress_widget.update_status("压缩已取消")
    
    def on_compression_ratio_changed(self, ratio: float):
        """压缩比例改变时的处理"""
        # 计算并显示预估输出大小
        self.update_estimated_output_size(ratio)
    
    def update_estimated_output_size(self, ratio: float):
        """更新预估输出大小显示"""
        try:
            # 获取当前文件路径列表
            file_paths = self.file_list.get_file_paths()
            if not file_paths:
                # 没有文件时显示默认信息
                self.compression_settings.update_estimated_size("--")
                return
            
            # 计算所有文件的预估总大小
            total_estimated_size = 0
            total_original_size = 0
            
            for file_path in file_paths:
                original_size = FileHandler.get_file_size_bytes(file_path)
                if original_size > 0:
                    total_original_size += original_size
                    # 计算单个文件的预估大小
                    scale_ratio = 1.0 - ratio
                    size_ratio = scale_ratio ** 2
                    
                    if ratio == 0:
                        estimated_size = original_size
                    elif ratio <= 0.3:
                        estimated_size = original_size * size_ratio * 0.8
                    elif ratio <= 0.6:
                        estimated_size = original_size * size_ratio * 0.6
                    else:
                        estimated_size = original_size * size_ratio * 0.4
                    
                    total_estimated_size += estimated_size
            
            if total_original_size > 0:
                # 格式化显示
                original_size_str = FileHandler.format_size_bytes(total_original_size)
                estimated_size_str = FileHandler.format_size_bytes(int(total_estimated_size))
                compression_percentage = ((total_original_size - total_estimated_size) / total_original_size) * 100
                
                display_text = f"预估输出大小: {estimated_size_str} (原大小: {original_size_str}, 节省: {compression_percentage:.1f}%)"
                self.compression_settings.update_estimated_size(display_text)
            else:
                self.compression_settings.update_estimated_size("无法计算预估大小")
                
        except Exception as e:
            logger.error(f"计算预估输出大小失败: {e}")
            self.compression_settings.update_estimated_size("计算失败")
    
    def on_file_progress_updated(self, progress: int):
        """文件进度更新"""
        self.progress_widget.update_current_progress(progress)
    
    def on_file_status_updated(self, status: str):
        """文件状态更新"""
        self.progress_widget.update_status(status)
    
    def on_file_compression_finished(self, success: bool, message: str):
        """文件压缩完成"""
        print(f"[GUI] 收到压缩完成回调: success={success}, message={message}")
        self.completed_files += 1
        
        # 更新总体进度
        overall_progress = int((self.completed_files / self.total_files) * 100)
        self.progress_widget.update_overall_progress(overall_progress)
        
        if success:
            print(f"[GUI] 显示成功消息: {message}")
            self.show_message(f"压缩完成: {message}", "成功")
        else:
            print(f"[GUI] 显示错误消息: {message}")
            self.show_message(f"压缩失败: {message}", "错误")
        
        # 检查是否所有文件都处理完成
        if self.completed_files >= self.total_files:
            print(f"[GUI] 所有文件处理完成，启用压缩按钮")
            self.compression_settings.set_compression_enabled(True)
            self.operation_control.set_compression_enabled(True)
            self.progress_widget.update_status("所有文件处理完成")
            self.current_workers.clear()
    
    def on_file_info_updated(self, info: Dict):
        """文件信息更新"""
        self.progress_widget.update_file_info(info)
    
    def update_progress(self):
        """更新进度（定时器调用）"""
        # 清理已完成的工作线程
        self.compressor.cleanup_finished_workers()
    
    def show_message(self, message: str, title: str = "提示"):
        """显示消息框"""
        msg_box = QMessageBox(self)
        msg_box.setWindowTitle(title)
        msg_box.setText(message)
        
        if title == "错误":
            msg_box.setIcon(QMessageBox.Icon.Critical)
        elif title == "警告":
            msg_box.setIcon(QMessageBox.Icon.Warning)
        elif title == "成功":
            msg_box.setIcon(QMessageBox.Icon.Information)
        else:
            msg_box.setIcon(QMessageBox.Icon.Information)
        
        msg_box.exec()
    
    def closeEvent(self, event):
        """窗口关闭事件"""
        if self.current_workers:
            reply = QMessageBox.question(
                self, "确认退出", "有压缩任务正在进行中，确定要退出吗？",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
            )
            if reply == QMessageBox.StandardButton.Yes:
                self.compressor.cancel_all()
                event.accept()
            else:
                event.ignore()
        else:
            event.accept()
    
    def set_window_icon(self):
        """设置窗口图标"""
        try:
            # 获取项目根目录的绝对路径
            current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            window_config = get_window_config()
            icon_path = os.path.join(current_dir, window_config['icon'])
            
            # 检查图标文件是否存在
            if os.path.exists(icon_path):
                icon = QIcon(icon_path)
                self.setWindowIcon(icon)
                logger.info(f"成功设置窗口图标: {icon_path}")
            else:
                logger.warning(f"图标文件不存在: {icon_path}")
        except Exception as e:
            logger.error(f"设置窗口图标失败: {e}", exc_info=True)
